package com.dayang.homemaking.common.module.desensitization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: dayang
 * @since: 2024/9/18
 * @description: 自定义序列化类，用于数据脱敏处理
 */
@NoArgsConstructor
@AllArgsConstructor
public class DesensitizationSerialize extends JsonSerializer<String> implements ContextualSerializer{
    private DesensitizationTypeEnum type;
    private Integer startInclude;
    private Integer endExclude;
    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(type.desensitize(s,startInclude,endExclude));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null){
            if (Objects.equals(beanProperty.getType().getRawClass(),String.class)){
                Desensitization desensitization = beanProperty.getAnnotation(Desensitization.class);
                if (desensitization == null){
                    desensitization = beanProperty.getContextAnnotation(Desensitization.class);
                }
                if (desensitization != null){
                    return new DesensitizationSerialize(desensitization.type(),desensitization.startInclude(),desensitization.endExclude());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
        }
        return serializerProvider.findNullValueSerializer(beanProperty);
    }
}
